package com.cupk.rotaryguard.monitor.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cupk.rotaryguard.monitor.entity.DeviceDiagnosis;
import com.cupk.rotaryguard.monitor.entity.DeviceInfo;
import com.cupk.rotaryguard.monitor.entity.WarningInfo;
import com.cupk.rotaryguard.monitor.mapper.DeviceMapper;
import com.cupk.rotaryguard.monitor.mapper.DiagnosisMapper;
import com.cupk.rotaryguard.monitor.mapper.MonitorRecordMapper;
import com.cupk.rotaryguard.monitor.mapper.WarningMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author tjy
 * @date 2023/4/17
 * @apiNote
 */
@Component
public class WarningGenerateJob {
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private DiagnosisMapper diagnosisMapper;

    @Resource
    private WarningMapper warningMapper;

    /**
     * 定制预警任务
     */
    @XxlJob("warningGenerate")
    public void warningGenerate() {
        List<DeviceInfo> deviceInfos = deviceMapper.selectList(null);
        for (DeviceInfo device : deviceInfos) {
            //根据设备号获取最新状态诊断预测结果
            QueryWrapper<DeviceDiagnosis> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("device_id", device.getId())
                    .orderByDesc("diagnosis_time").last("limit 1");
            DeviceDiagnosis diagnosis = diagnosisMapper.selectOne(queryWrapper);
            String diagnosisRes = diagnosis.getDiagnosisRes();
            if (!diagnosisRes.equals("正常")) {
                //生成预警信息
                WarningInfo warningInfo = new WarningInfo();
                warningInfo.setDeviceId(device.getId());
                warningInfo.setDeviceModel(device.getDeviceModel());
                warningInfo.setDeviceFault(diagnosisRes);
                warningMapper.insert(warningInfo);
            }
        }
    }
}
